trigger Productivity_Allocation_Insert on Opportunity (after insert, after update) {
    list<Productivity_Allocations__c> productivityAllocationList = new list<Productivity_Allocations__c>{};

    if(Trigger.isInsert)
    {
        for( Opportunity o : Trigger.new )
        {
            Productivity_Allocations__c pa = new Productivity_Allocations__c(
                Opportunity_Name__c = o.Id,
                Sales_Associate__c = O.OwnerId,
                Allocation_Percentage__c = 100.0
            );
            productivityAllocationList.add(pa);
        }//end of for
        insert productivityAllocationList;
    }//end of if(Trigger.isInsert.)
    
    if(Trigger.isUpdate)
    {
        List<ID> oppurtunityOwnerChangedIdList = new List<ID>();
    
        for(Opportunity o: Trigger.new)
        {
            if(o.ownerid != Trigger.oldMap.get(o.id).ownerid)
            {
                oppurtunityOwnerChangedIdList.add(o.id);
            }
        }
        if(oppurtunityOwnerChangedIdList.size() > 0)
        {
            List<Opportunity> opportunityList = [select id, ownerid, Split_Opportunity_PA__c, (select Sales_Associate__c, Opportunity_Name__c from Productivity_Allocations__r order by createddate) from Opportunity where id in :oppurtunityOwnerChangedIdList];
                    
            List<Productivity_Allocations__c> paListToBeUpdated = new List<Productivity_Allocations__c>();
            Integer count = 0;
            
            for(Opportunity o: opportunityList)
            {
                count = 0;
                if(o.Productivity_Allocations__r.size() > 1)
                {
                    for(Productivity_Allocations__c pa: o.Productivity_Allocations__r)
                    {
                        if(count == 0)
                        {
                            pa.Sales_Associate__c = Trigger.newMap.get(pa.Opportunity_Name__c).ownerid;
                            paListToBeUpdated.add(pa);
                            break;
                        }
                    }
                }
                if(o.Productivity_Allocations__r.size() == 1)
                {
                    Productivity_Allocations__c pa = o.Productivity_Allocations__r[0];
                    pa.Sales_Associate__c = Trigger.newMap.get(pa.Opportunity_Name__c).ownerid;
                    paListToBeUpdated.add(pa);
                }
            }       
            if(paListToBeUpdated.size() > 0)
                update paListToBeUpdated;
        }
    } 
}